<template>
  <el-dialog v-model="visible" :show-close="false" width="500" align-center>
    <template #header="{ close }">
      <div class="flex justify-between items-center">
        <img src="@/assets/images/logo.png" class="h-8" />
        <img src="@/assets/images/close.png" class="w-8 h-8 cursor-pointer" @click="close" />
      </div>
    </template>
    <div class="flex justify-center flex-col">
      <p class="text-center text-xl font-bold text-black mb-6">登 录</p>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        size="large"
        label-width="auto"
        class="demo-ruleForm">
        <el-form-item prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入用户名/手机号" maxlength="11" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button class="w-full mt-6 mb-4" type="primary" @click="submitForm(ruleFormRef)">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus' // 使用 InternalRuleItem 类型
  import { useUserStore } from '@/stores'

  const visible = defineModel('modelValue', {
    required: true
  })
  const ruleFormRef = ref<FormInstance>()
  //   const validateName = (rule: any, value: string, callback: (error?: Error) => void) => {
  //     if (value === '') {
  //       callback(new Error('请输入用户名/手机号'))
  //     } else {
  //       callback()
  //     }
  //   }

  const ruleForm = reactive({
    name: '',
    password: ''
  })

  const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入用户名/手机号', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  })
  const userStore = useUserStore()
  const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(valid => {
      if (valid) {
        if (ruleForm.name !== 'admin') {
          ElMessage.error('该用户不存在')
          return
        }
        if (ruleForm.password !== 'hmxx2025') {
          ElMessage.error('用户名或密码错误')
          return
        }
        userStore.setUser({ name: ruleForm.name })
        visible.value = false
      }
    })
  }
</script>

<style scoped></style>
